<script setup lang="ts">
import { queryBuild, queryBuildDetail } from '@/api';
import PageStatus from '@/components/page-status/index.vue';
import { ADD_TYPE_ENUM } from '@/const';
import type { BuildDetail, BuildItem, Current } from '@/types';
import { onMounted, reactive, ref } from 'vue';
import AddBuilding from './add-building.vue';
import BuildingDetail from './building-detail.vue';
import BuildingDisplay from './building-display.vue';
import Floor from './floor.vue';

const buildLoading = ref(true);
const loading = ref(true);
const building = ref<BuildItem[]>([]);
const current = reactive<Partial<Current>>({});
const selectBuild = ref<BuildDetail>({});

const updateBuildingList = () => {
	queryBuild().then((res) => {
		if (res.Code === 200) {
			building.value = res.Data.Apartments || []
		}
	}).finally(() => {
		buildLoading.value = false;
	});
}

const updateBuildDetail = () => {
	queryBuildDetail(current.building || 0).then((res) => {
		if (res.Code === 200) {
			selectBuild.value = res.Data || {};
		}
	}).finally(() => {
		loading.value = false;
	});
}

const changeBuilding = (key: number) => {
	current.building = key;
	loading.value = true;
	updateBuildDetail();
}

onMounted(() => {
	updateBuildingList();
});

</script>

<template>
	<PageStatus :loading="buildLoading" :empty="!building.length">
		<template #empty>
			<AddBuilding :current :type="ADD_TYPE_ENUM.building" @add="updateBuildingList"></AddBuilding>
		</template>
		<div class="form-wrap pt10">
			<div class="flex items-center mb10">
				<div class="flex-1">
					<BuildingDisplay @update="updateBuildingList" :items="building" @change="changeBuilding">
					</BuildingDisplay>
				</div>
				<AddBuilding :current :type="ADD_TYPE_ENUM.building" @add="updateBuildingList"></AddBuilding>
			</div>
			<BuildingDetail :item="{}"></BuildingDetail>
		</div>
		<PageStatus :loading="loading" :empty="!selectBuild.Floors?.length">
			<template #empty>
				<AddBuilding :type="ADD_TYPE_ENUM.floor" :current="current" @add="updateBuildDetail">
					暂无楼层，请点击
					<a-button type="primary" ghost class="border-none pl0">
						添加楼层
					</a-button>
				</AddBuilding>
			</template>
			<div class="form-wrap pt0">
				<AddBuilding :type="ADD_TYPE_ENUM.floor" :current @add="updateBuildDetail">
					<a-button type="primary" ghost block class="mb10">
						+ 添加楼层
					</a-button>
				</AddBuilding>
				<Floor :data="selectBuild" :current="current" @on-success="updateBuildDetail"></Floor>
			</div>
		</PageStatus>
	</PageStatus>
</template>
<style scoped></style>
